<template>
    <div class="app-container">
        <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" inline v-show="showSearch" label-width="68px">
            <el-form-item label="类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
                    <el-option v-for="dict in dict.type.slquestion_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="材料" prop="materials">
        <el-input
          v-model="queryParams.materials"
          placeholder="请输入材料中的部分内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['business:slquestion:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['business:slquestion:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['business:slquestion:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['business:slquestion:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="slquestionList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="id" />
            <el-table-column label="类型" align="center" prop="type">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.slquestion_type" :value="scope.row.type" />
                </template>
            </el-table-column>
            <el-table-column label="材料" align="center" prop="materials">
                <template slot-scope="scope">
                    <span v-if="scope.row.materials.length > 20">{{ scope.row.materials.slice(0, 20) }}...</span>
                    <span v-else>{{ scope.row.materials }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:slquestion:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['business:slquestion:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改申论题库管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <!-- 材料 -->
                <div v-for="(material, index) in form.materials" :key="index">
                    <el-form-item :label="'资料' + getChineseNumber(index + 1)">
                        <editor v-model="form.materials[index]" :min-height="192" />
                        <el-button size="mini" type="danger" @click="removeMaterial(index)">删除当前'给定资料'</el-button>
                    </el-form-item>
                </div>
                <el-button size="mini" type="primary" @click="addMaterial">添加'给定资料'</el-button>
				<el-divider><i class="el-icon-caret-bottom"></i></el-divider>

                <!-- 题干 -->
                <div v-for="(content, index) in form.content" :key="index">
                    <el-form-item :label="getChineseNumber(index + 1)">
                        <editor v-model="form.content[index]" :min-height="192" />
                        <el-button size="mini" type="danger" @click="removeContent(index)">删除当前'作答要求'</el-button>
                    </el-form-item>
                </div>
                <el-button size="mini" type="primary" @click="addContent">添加'作答要求'</el-button>
                <el-divider><i class="el-icon-caret-bottom"></i></el-divider>

                <!-- 参考答案 -->
                <div v-for="(answer, index) in form.suggestedAnswer" :key="index">
                    <el-form-item :label="'参考答案' + getChineseNumber(index + 1)">
                        <editor v-model="form.suggestedAnswer[index]" :min-height="192" />
                        <el-button size="mini" type="danger" @click="removeAnswer(index)">删除当前参考答案</el-button>
                    </el-form-item>
                </div>
                <el-button size="mini" type="primary" @click="addAnswer">添加答案</el-button>

                <el-form-item label="类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择类型">
                        <el-option v-for="dict in dict.type.slquestion_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listSlquestion, getSlquestion, delSlquestion, addSlquestion, updateSlquestion } from "@/api/business/slquestion";
import { allCorrects, delCorrect } from "@/api/business/correct";

export default {
    name: "Slquestion",
    dicts: ['slquestion_type'],
    data() {
        return {
            loading: true,
            ids: [],
            single: true,
            multiple: true,
            showSearch: true,
            total: 0,
            slquestionList: [],
            title: "",
            open: false,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                materials: null,
                content: null,
                suggestedAnswer: null,
                type: null
            },
            form: {
                id: null,
                materials: [],
                content: [],
                suggestedAnswer: [],
                type: null
            },
			rules: {
                        type: [
                    { required: true, message: "类型不能为空", trigger: "change" }
                  ]
        }
        };
    },
    created() {
        this.getList();
    },
    methods: {
        addMaterial() {
            this.form.materials.push(""); // 添加一个新的空材料
        },
        removeMaterial(index) {
            this.form.materials.splice(index, 1); // 删除指定索引的材料
        },
        addContent() {
            this.form.content.push(""); // 添加一个新的空题干
        },
        removeContent(index) {
            this.form.content.splice(index, 1); // 删除指定索引的题干
        },
        addAnswer() {
            this.form.suggestedAnswer.push(""); // 添加一个新的空参考答案
        },
        removeAnswer(index) {
            this.form.suggestedAnswer.splice(index, 1); // 删除指定索引的参考答案
        },
        getList() {
            this.loading = true;
            listSlquestion(this.queryParams).then(response => {
                this.slquestionList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        cancel() {
            this.open = false;
            this.reset();
        },
        reset() {
            this.form = {
                id: null,
                materials: [],
                content: [],
                suggestedAnswer: [],
                type: null
            };
            this.resetForm("form");
        },
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加申论题库管理";
        },
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getSlquestion(id).then(response => {
                this.form = response.data;
                this.form.materials = JSON.parse(response.data.materials);
                this.form.content = JSON.parse(response.data.content);
                this.form.suggestedAnswer = JSON.parse(response.data.suggestedAnswer);
                this.open = true;
                this.title = "修改申论题库管理";
            });
        },
        submitForm() {
    // 将数组转换为 JSON 字符串
    const materials = JSON.stringify(this.form.materials);
    const content = JSON.stringify(this.form.content);
    const suggestedAnswer = JSON.stringify(this.form.suggestedAnswer);

    // 验证表单
    this.$refs["form"].validate(valid => {
        if (valid) {
            // 使用 nextTick 确保 DOM 更新后执行
            this.$nextTick(() => {
                if (this.form.id != null) {
                    updateSlquestion({ ...this.form, materials, content, suggestedAnswer }).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open = false;
                        this.getList();
                    });
                } else {
                    addSlquestion({ ...this.form, materials, content, suggestedAnswer }).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
            });
        }
    });
},
handleDelete(row) {
    const ids = row.id || this.ids;
    this.$modal.confirm('删除操作是不可逆的，是否确认删除？').then(() => {
        // 查询与 slquestion 相关的 correct
        return allCorrects({ questionId: ids }); // 假设这里的参数为 questionId
    }).then(response => {
        // 打印返回的 correct 数据
        const correctIds = response.data.map(item => item.id);
        console.log('准备删除的 correct ID:', correctIds);

        // 删除所有相关的 correct
        const deletePromises = correctIds.map(id => {
            return delCorrect(id); // 假设 delCorrect 是删除 correct 的 API
        });

        return Promise.all(deletePromises);
    }).then(() => {
        // 删除 slquestion
        return delSlquestion(ids);
    }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
    }).catch(error => {
        console.error('删除过程中发生错误:', error);
    });
},
        handleExport() {
            this.download('business/slquestion/export', {
                ...this.queryParams
            }, `slquestion_${new Date().getTime()}.xlsx`);
        },
        getChineseNumber(num) {
            const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
            return chineseNumbers[num] || '';
        }
    }
};
</script>
